import xml.etree.ElementTree as ET
from typing import Dict, List
from get_kodi_info import kodi_jsonrpc  # 添加这行导入

def parse_smart_playlist(xsp_path):
    """解析智能播放列表文件(.xsp)获取规则"""
    try:
        tree = ET.parse(xsp_path)
        root = tree.getroot()
        playlist_type = root.attrib.get('type', '')
        match_elem = root.find('match')
        match_type = match_elem.text if match_elem is not None else 'all'
        rules = []
        for rule_elem in root.findall('rule'):
            field = rule_elem.attrib.get('field', '')
            operator = rule_elem.attrib.get('operator', 'contains')
            value_elem = rule_elem.find('value')
            value = value_elem.text if value_elem is not None else ''
            rules.append({
                "field": field,
                "operator": operator,
                "value": value
            })
        return playlist_type, match_type, rules
    except Exception as e:
        raise RuntimeError(f"解析播放列表文件失败: {str(e)}")

def build_jsonrpc_filter(rules, match_type):
    """将智能播放列表规则转换为JSON-RPC过滤器"""
    if not rules:
        return {}
    if len(rules) == 1:
        rule = rules[0]
        return {
            "field": rule["field"],
            "operator": rule["operator"],
            "value": rule["value"]
        }
    logical_operator = "and" if match_type.lower() == "all" else "or"
    return {
        logical_operator: [
            {"field": rule["field"], "operator": rule["operator"], "value": rule["value"]}
            for rule in rules
        ]
    }

def get_media_by_rules(playlist_type, rules, match_type, credentials):
    """根据规则获取媒体项目"""
    media_filter = build_jsonrpc_filter(rules, match_type)
    if playlist_type == "movies":
        method = "VideoLibrary.GetMovies"
        properties = ["title", "year", "genre", "rating", "file", "art"]
    elif playlist_type == "tvshows":
        method = "VideoLibrary.GetTVShows"
        properties = ["title", "year", "genre", "rating", "file", "art"]
    elif playlist_type == "episodes":
        method = "VideoLibrary.GetEpisodes"
        properties = ["title", "showtitle", "season", "episode", "file", "art"]
    elif playlist_type == "songs":
        method = "AudioLibrary.GetSongs"
        properties = ["title", "artist", "album", "year", "genre", "file", "art"]
    else:
        raise ValueError(f"不支持的播放列表类型: {playlist_type}")
    params = {
        "properties": properties,
        "filter": media_filter,
        "limits": {"start": 0, "end": 500}
    }
    response = kodi_jsonrpc(method, params, credentials)  # 现在应该能找到这个函数
    result_key = {
        "movies": "movies",
        "tvshows": "tvshows",
        "episodes": "episodes",
        "songs": "songs"
    }.get(playlist_type)
    return response.get("result", {}).get(result_key, [])

def get_playlist_items(playlist_path, credentials):
    """获取智能播放列表内容"""
    try:
        playlist_type, match_type, rules = parse_smart_playlist(playlist_path)
        return get_media_by_rules(playlist_type, rules, match_type, credentials)
    except Exception as e:
        print(f"获取播放列表失败: {str(e)}")
        return []
